import { getRegeo } from '@/api/index.js'
import store from '@/store/index.js'
/**
 * 地址管理工具函数
 */

/**
 * 格式化地址显示
 * @param {Object} address 地址对象
 * @returns {String} 格式化后的地址字符串
 */
export function formatAddress(address) {
    if (!address) return '';
    
    const { province_name, city_name, district_name, address: detail } = address;
    const parts = [province_name, city_name, district_name, detail].filter(Boolean);
    return parts.join(' ');
}

/**
 * 检查地址是否完整
 * @param {Object} address 地址对象
 * @returns {Boolean} 是否完整
 */
export function isAddressComplete(address) {
    if (!address) return false;
    
    const required = ['name', 'telephone', 'province_id', 'city_id', 'district_id', 'address'];
    return required.every(field => address[field] && address[field] !== '');
}

/**
 * 验证手机号格式
 * @param {String} phone 手机号
 * @returns {Boolean} 是否有效
 */
export function isValidPhone(phone) {
    return /^1[3-9]\d{9}$/.test(phone);
}

/**
 * 获取地址选择器的列数据
 * @param {Array} provinceList 省份列表
 * @param {Array} cityList 城市列表
 * @param {Array} districtList 区县列表
 * @returns {Array} 列数据
 */
export function getRegionColumns(provinceList = [], cityList = [], districtList = []) {
    const provinceNames = provinceList.map(item => item?.name || '').filter(Boolean);
    const cityNames = cityList.map(item => item?.name || '').filter(Boolean);
    const districtNames = districtList.map(item => item?.name || '').filter(Boolean);
    
    return [provinceNames, cityNames, districtNames];
}

/**
 * 获取经纬度和位置
 * @param {Object} addressComponent 经纬度和位置
 * @returns {Object} 经纬度和位置
 * @param {Number} latitude 经度
 * @param {Number} longitude 纬度
 */

export async function getRegeoEvent(location) {
    const res = await getRegeo({
        location: location,
    })
    // 高德返回结构：res.data.regeocode.addressComponent
    try {
        const addressComponent = res && res.data && res.data.regeocode && res.data.regeocode.addressComponent
        if (addressComponent && store && store.commit) {
            store.commit('SET_ADDRESS_COMPONENT', addressComponent)
        }
    } catch (e) {
        console.log('解析地址组件失败', e)
    }
}
